package com.winit.openapi.isp.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.ContractService;
import com.winit.erp.spi.bpartner.command.ContractCommand;
import com.winit.oms.spi.isp.DeliveryService;
import com.winit.oms.spi.isp.command.DeliveryCommand;
import com.winit.oms.spi.vo.DeliveryResult;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 发货相关操作接口 目前有确认发货、取消发货
 * 
 * @version <pre>
 * Author   Version     Date        Changes
 * bing.gu  1.0         2015年6月4日   Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/isp/delivery")
public class DeliveryController extends BaseController {

    @Resource
    private ContractService agreementService;

    @Resource
    DeliveryService         deliveryService;

    /**
     * 批量确认发货
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchConfirm")
    public String batchConfirm(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();

        List<String> list = new ArrayList<String>();

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.validList(json, "orderNoList", true);
            JSONArray packageList = json.getJSONArray("orderNoList");
            for (Object object : packageList) {
                JSONObject noObj = (JSONObject) object;
                ValidateUtil.validNotNull(noObj, "orderNo");
                ValidateUtil.validMaxLength(noObj, "orderNo", 60);
                list.add(noObj.getString("orderNo").trim());
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口创建订单
        DeliveryCommand command = new DeliveryCommand();
        command.setList(list);
        DeliveryResult result = new DeliveryResult();
        // result.setSuccess(true);
        // result.setFaildCount(10);
        // result.setSuccessCount(12);
        result = deliveryService.confirmDelivery(command);

        if (result.isSuccess()) {
            // 返回操作结果
            Map<String, Integer> data = new HashMap<String, Integer>();
            data.put("successCount", result.getSuccessCount());
            data.put("failedCount", result.getFaildCount());
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.CONFIRM_DELIVERY_FAILD);
        }

        return SUCCESS;
    }

    /**
     * 批量取消发货
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchCancel")
    public String batchCancel(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();

        List<String> list = new ArrayList<String>();

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.validList(json, "orderNoList", true);
            JSONArray packageList = json.getJSONArray("orderNoList");
            for (Object object : packageList) {
                JSONObject noObj = (JSONObject) object;
                ValidateUtil.validNotNull(noObj, "orderNo");
                ValidateUtil.validMaxLength(noObj, "orderNo", 60);
                list.add(noObj.getString("orderNo").trim());
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口创建订单
        DeliveryCommand command = new DeliveryCommand();
        command.setList(list);
        DeliveryResult result = new DeliveryResult();
//        result.setSuccess(true);
//        result.setFaildCount(10);
//        result.setSuccessCount(12);
         result = deliveryService.cancelDelivery(command);

        if (result.isSuccess()) {
            // 返回操作结果
            Map<String, Integer> data = new HashMap<String, Integer>();
            data.put("successCount", result.getSuccessCount());
            data.put("failedCount", result.getFaildCount());
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.CANCEL_DELIVERY_FAILD);
        }

        return SUCCESS;
    }

    /**
     * 单个确认发货
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/confirm")
    public String confirm(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();

        List<String> list = new ArrayList<String>();

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.validNotNull(json, "orderNo");
            ValidateUtil.validMaxLength(json, "orderNo", 60);
            list.add(json.getString("orderNo").trim());
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口创建订单
        DeliveryCommand command = new DeliveryCommand();
        command.setList(list);
        DeliveryResult result = new DeliveryResult();
//        result.setSuccess(true);
//        result.setFaildCount(10);
//        result.setSuccessCount(12);
         result = deliveryService.confirmDelivery(command);

        if (result.isSuccess()) {
            // 返回操作结果
            Map<String, Boolean> data = new HashMap<String, Boolean>();
            data.put("success", true);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.CONFIRM_DELIVERY_FAILD);
        }

        return SUCCESS;
    }

    /**
     * 单个取消发货
     * 2016-11-22日 停用，马健留
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/cancel")
    public String cancel(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        throw new ApiException(ErrorCode.API_STOP);
    }

    // 校验用户是不是isp用户
    private void checkIspRight() {
        ContractCommand command = new ContractCommand();
        command.setBusiType("ISP");
        command.setBpartnerId(Long.parseLong(CommandContext.getContext().getUserId()));
        boolean rightStatus = agreementService.isOpenContract(command);

        if (!rightStatus) {
            throw new ApiException(ErrorCode.USERNAME_ISNOT_ISP_USER);
        }

    }

}
